package com.unsins.core.session;

import com.unsins.core.cache.sessioncache.ISessionCache;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * Created by IntelliJ IDEA.
 * User: odpsoft
 * Date: 2009-4-16
 * Time: 18:34:02
 */
public final class SessionManagerUtils {
    private final static String SESSION_ID = "sessionid";

    private static ISessionCache memcachedClient = null;

    public void setMemcached(ISessionCache mc) {
        memcachedClient = mc;
    }

    public void setSessionAttribute(final HttpServletRequest request, final Object attributeObject) {
        HttpSession session = request.getSession();
        String sessionKey = (String) session.getAttribute(SESSION_ID);

        if (StringUtils.isBlank(sessionKey)) {
            UUID uuid = UUID.randomUUID();
            request.getSession().setAttribute(SESSION_ID, uuid.toString());
            memcachedClient.setAttribute(uuid.toString(), attributeObject);
        } else {
            memcachedClient.setAttribute(sessionKey, attributeObject);
        }
    }

    public Object getSessionAttribute(final HttpServletRequest request) {
        String uuid = (String) request.getSession().getAttribute(SESSION_ID);
        if (StringUtils.isNotBlank(uuid)) {
            return memcachedClient.getAttribute(uuid);
        } else {
            return null;
        }
    }
}
